<?php
session_start();

if (!isset($_SESSION['username'])) {
    header("Location: ../login.php");
    exit();
}

// 数据库配置
include 'config.php';

// 接收卡密数量和类型
$count = isset($_GET['count']) ? intval($_GET['count']) : 0;
$type = isset($_GET['type']) ? $conn->real_escape_string($_GET['type']) : null;

if ($count <= 0 || $type === null) {
    echo json_encode(array("code" => "403", "error" => "参数不全或数量无效"));
    exit();
}

// 生成随机卡密
function generateKami($length = 12) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

// 检查数据库中是否已经存在相同的卡密
function isKamiExists($conn, $kami) {
    $checkSql = "SELECT COUNT(*) FROM kami WHERE kami = ?";
    $stmt = $conn->prepare($checkSql);
    $stmt->bind_param("s", $kami);
    $stmt->execute();
    $stmt->bind_result($count);
    $stmt->fetch();
    $stmt->close();
    return $count > 0;
}

// 生成并插入卡密
$successCount = 0;
$insertSql = "INSERT INTO kami (kami, type, zt, vip_time, qq) VALUES (?, ?, 0, '', '')";
$stmt = $conn->prepare($insertSql);

for ($i = 0; $i < $count; $i++) {
    $kami = generateKami();
    if (!isKamiExists($conn, $kami)) {
        $stmt->bind_param("ss", $kami, $type);
        if ($stmt->execute()) {
            $successCount++;
        } else {
            echo json_encode(array("code" => "404", "error" => $conn->error));
            $stmt->close();
            $conn->close();
            exit();
        }
    }
}

echo json_encode(array("code" => "200", "msg" => "卡密批量生成并添加成功", "count" => $successCount));
$stmt->close();
$conn->close();
?>
